import type { Pinia } from 'pinia'

import type { App } from 'vue'

import { createPinia } from 'pinia'
import { APP_PREFIX } from '@/enums/appEnum'

let pinia: Pinia

/**
 * 注册状态
 * @param app
 */
export async function setupStore(app: App) {
  const { createPersistedState } = await import('pinia-plugin-persistedstate')
  pinia = createPinia()
  pinia.use(
    createPersistedState({
      key: (storeKey) => `${APP_PREFIX}${storeKey}`,
      storage: localStorage,
    }),
  )
  app.use(pinia)
  return pinia
}

/**
 * 重置所有存储
 */
export function resetAllStores(cb?: () => void) {
  if (!pinia) {
    console.error('Pinia is not installed')
    return
  }
  const allStores = (pinia as any)._s
  for (const [_key, store] of allStores) {
    store.$reset()
  }
  cb?.()
}
